package cn.androidstudy.musicsimple;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Environment.DIRECTORY_MUSIC;

public class MainActivity extends AppCompatActivity {
    private static final File PATH = Environment.getExternalStorageDirectory();// 获取SD卡总目录。
    public List<String> musicList;// 存放找到的所有mp3的绝对路径。
    public List<String> musicNameList;// 存放找到的所有mp3的文件名。
    public MediaPlayer player; // 定义多媒体对象
    public int songNum; // 当前播放的歌曲在List中的下标,flag为标致
    public String songName; // 当前播放的歌曲名
    private SeekBar seekBar;
    private TextView txtInfo;
    private int flag = 1;

    private TimerTask timerTask;//定时任务
    private Timer timer;//定时器
    private boolean isStart=false;//避免定时器重复启动


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File externalFilesDir = getExternalFilesDir(DIRECTORY_MUSIC);
        ///storage/emulated/0/Android/data/cn.androidstudy.musicsimple/files/Music
        System.out.println(externalFilesDir.getAbsolutePath());
        ///storage/emulated/0
        System.out.println(PATH.getAbsolutePath());

        timerTask=new TimerTask() {
            @Override
            public void run() {
                seekBar.setProgress(player.getCurrentPosition());
            }
        };
        timer=new Timer();

        player = new MediaPlayer();
        txtInfo=findViewById(R.id.tv1);
        musicList = new ArrayList<>();
        musicNameList = new ArrayList<>();
        try {
            File MUSIC_PATH = new File(PATH, "Music");//获取根目录的二级目录Music
            System.out.println(MUSIC_PATH.getAbsolutePath());

            if (MUSIC_PATH.listFiles(new MusicFilter()).length > 0) {
                for (File file : MUSIC_PATH.listFiles(new MusicFilter())) {
                    musicList.add(file.getAbsolutePath());
                    musicNameList.add(file.getName());
                    //Log.i("TAG", file.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            Log.i("TAG", "读取文件异常");
            //Log.i("TAG", e.getMessage());
        }

        ListView listView = findViewById(R.id.lv1);
        listView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                musicNameList));
        //添加item单击事件处理
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                songNum = position;
                play();
                flag++;
                if(!isStart) {
                    timer.schedule(timerTask, 0, 1000);
                    isStart=true;
                }
            }
        });

        Button btnStart = findViewById(R.id.btn_star);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    /**
                     * 引入flag作为标志，当flag为1 的时候，此时player内没有东西，所以执行musicService.play()函数
                     * 进行第一次播放，然后flag自增二不再进行第一次播放
                     * 当再次点击“开始/暂停”按钮次数即大于1 将执行暂停或继续播放goplay()函数
                     */
                    if (flag == 1) {
                        play();
                        flag++;
                    } else {
                        if (!player.isPlaying()) {
                            goPlay();
                        } else if (player.isPlaying()) {
                            pause();
                        }
                    }
                } catch (Exception e) {
                    Log.i("LAT", "开始异常！");
                }

            }
        });

        Button btnStop = findViewById(R.id.btn_stop);
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    stop();
                    flag = 1;//当点击停止按钮时，flag置为1
                    seekBar.setProgress(0);
                    txtInfo.setText("播放已经停止");
                } catch (Exception e) {
                    Log.i("LAT", "停止异常！");
                }

            }
        });

        Button btnPre = findViewById(R.id.btn_last);
        btnPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    pre();
                } catch (Exception e) {
                    Log.i("LAT", "上一曲异常！");
                }

            }
        });

        Button btnNext = findViewById(R.id.btn_next);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    next();
                } catch (Exception e) {
                    Log.i("LAT", "下一曲异常！");
                }

            }
        });

        seekBar = findViewById(R.id.sb);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {//用于监听SeekBar进度值的改变

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {//用于监听SeekBar开始拖动

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {//用于监听SeekBar停止拖动  SeekBar停止拖动后的事件
                int progress = seekBar.getProgress();
                Log.i("TAG:", "" + progress + "");
                int musicMax = player.getDuration(); //得到该首歌曲最长秒数
                int seekBarMax = seekBar.getMax();
                player.seekTo(musicMax * progress / seekBarMax);//跳到该曲该秒
                //autoChange = true;
                //manulChange = false;
            }
        });
    }


    class MusicFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3"));//返回当前目录所有以.mp3结尾的文件
        }
    }

    public void setPlayName(String dataSource) {
        File file = new File(dataSource);//假设为D:\\dd.mp3
        String name = file.getName();//name=dd.mp3
        int index = name.lastIndexOf(".");//找到最后一个 .
        songName = name.substring(0, index);//截取为dd
    }

    public void play() {
        try {
            player.reset(); //重置多媒体
            String dataSource = musicList.get(songNum);//得到当前播放音乐的路径
            setPlayName(dataSource);//截取歌名
            // 指定参数为音频文件
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setDataSource(dataSource);//为多媒体对象设置播放路径
            player.prepare();//准备播放
            player.start();//开始播放
            //setOnCompletionListener 当当前多媒体对象播放完成时发生的事件
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer arg0) {
                    next();//如果当前歌曲播放完毕,自动播放下一首.
                }
            });
            txtInfo.setText("歌曲："+songName+" 正在播放");
            seekBar.setMax(player.getDuration());

        } catch (Exception e) {
            Log.v("MusicService", e.getMessage());
        }
    }

    //继续播放
    public void goPlay() {
        int position = getCurrentProgress();
        player.seekTo(position);//设置当前MediaPlayer的播放位置，单位是毫秒。
        try {
            player.prepare();//  同步的方式装载流媒体文件。
        } catch (Exception e) {
            e.printStackTrace();
        }
        player.start();
        txtInfo.setText(String.format("歌曲：%s 正在播放", songName));
    }

    // 获取当前进度
    public int getCurrentProgress() {
        assert player != null;
        if (player != null & player.isPlaying()) {
            return player.getCurrentPosition();
        } else if (player != null & (!player.isPlaying())) {
            return player.getCurrentPosition();
        }
        return 0;
    }

    public void next() {
        songNum = songNum == musicList.size() - 1 ? 0 : songNum + 1;
        play();
    }

    public void pre() {
        songNum = songNum == 0 ? musicList.size() - 1 : songNum - 1;
        play();
    }

    // 暂停播放
    public void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
            txtInfo.setText("歌曲："+songName+" 已暂停");
        }
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.reset();
            txtInfo.setText("歌曲："+songName+" 已停止");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isStart){
            timer.cancel();
        }
    }
}
